package com.qnzw.zjmy.utils.risk;

import static android.content.Context.MODE_PRIVATE;


import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.github.gzuliyujiang.oaid.DeviceIdentifier;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.scottyab.rootbeer.RootBeer;
import com.qnzw.zjmy.home.ui.enums.RedisEnum;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;


/**
 * 设备检测
 */
public class DeviceUtils {

    private static volatile DeviceUtils instance;

    private DeviceUtils() {
    }

    public static DeviceUtils getInstance() {
        if (ObjectUtil.isNull(instance)) {
            synchronized (DeviceUtils.class) {
                if (ObjectUtil.isNull(instance)) {
                    instance = new DeviceUtils();
                }
            }
        }
        return instance;
    }

    /**
     * 检测开发者模式是否启用
     *
     * @param context
     * @return
     */
    public boolean isDeveloperModeEnabled(Context context) {
        return Settings.Secure.getInt(context.getContentResolver(), Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0;
        //return false;
    }

    /**
     * 检测是否开启USB调试模式
     *
     * @param context
     * @return
     */
    public boolean isAdbEnabled(Context context) {
        return Settings.Secure.getInt(context.getContentResolver(), Settings.Global.ADB_ENABLED, 0) != 0;
        // return false;
    }

    /**
     * 验证是否root
     *
     * @param context
     * @return
     */
    public boolean isDeviceRooted(Context context) {
        RootBeer rootBeer = new RootBeer(context);
        return rootBeer.isRooted();
    }

    /**
     * 检测是否开启无障碍模式
     *
     * @param context
     * @return
     */
    public boolean isAccessibilityServiceEnabled(Context context) {
        return Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED, 0) != 0;
    }

    /**
     * 是否开启了代理
     *
     * @return
     */
    public boolean isWifiProxy() {
        String proxyAddress = System.getProperty("http.proxyHost");
        int proxyPort = 0;
        String portStr = System.getProperty("http.proxyPort");
        if (!StrUtil.isEmpty(portStr)) {
            proxyPort = Integer.parseInt(portStr);
        }
        boolean wifiProxy = !StrUtil.isEmpty(proxyAddress) && proxyPort != 0;
        return wifiProxy;
    }

    //获取设备信息

    /**
     * 应用包名
     *
     * @param context
     * @return
     */
    public String getPackageName(Context context) {
        return context.getPackageName();
    }

    /**
     * APP 名字
     *
     * @param context
     * @return
     */
    public String getAppName(Context context) {
        PackageManager packageManager = context.getPackageManager();
        ApplicationInfo appInfo = null;
        try {
            appInfo = packageManager.getApplicationInfo(getPackageName(context), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "unknown";
        }
        CharSequence appName = packageManager.getApplicationLabel(appInfo);
        return (String) appName;
    }

    /**
     * APP 名字
     *
     * @param context
     * @return
     */
    public String getAppName(Context context, String packageName) {
        PackageManager packageManager = context.getPackageManager();
        ApplicationInfo appInfo = null;
        try {
            appInfo = packageManager.getApplicationInfo(packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "unknown";
        }
        CharSequence appName = packageManager.getApplicationLabel(appInfo);
        return (String) appName;
    }

    /**
     * APP 版本号
     *
     * @return
     */
    public String getVersionName() {
        return "";
    }

    /**
     * APP SIM卡情况
     *
     * @return
     */
    public Integer getSim(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        int simState = telephonyManager.getSimState();
        if (simState == TelephonyManager.SIM_STATE_ABSENT) {
            // SIM卡未插入
            return 1;
        } else if (simState == TelephonyManager.SIM_STATE_UNKNOWN) {
            // 无法获取SIM卡状态
            return 2;
        } else {
            // SIM卡已插入
            return 2;
        }
    }

    /**
     * 获取MAC地址
     *
     * @return
     */
    public String getMacAddr(Context context) {
        String macAddress = "";
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                if (intf.getName().equalsIgnoreCase("wlan0")) {
                    byte[] mac = intf.getHardwareAddress();
                    if (mac == null) {
                        macAddress = "";
                    } else {
                        StringBuilder buf = new StringBuilder();
                        for (byte aMac : mac) {
                            buf.append(String.format("%02X:", aMac));
                        }
                        if (buf.length() > 0) {
                            buf.deleteCharAt(buf.length() - 1);
                        }
                        macAddress = buf.toString();
                    }
                    break;
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return macAddress;
    }

    /**
     * APP 运营商
     *
     * @return
     */
    public String getNetworkOperatorName(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        int simState = telephonyManager.getSimState();
        if (simState == TelephonyManager.SIM_STATE_ABSENT) {
            // SIM卡未插入
            return "";
        } else if (simState == TelephonyManager.SIM_STATE_UNKNOWN) {
            // 无法获取SIM卡状态
            return "";
        } else {
            // SIM卡已插入
            String operatorName = telephonyManager.getNetworkOperatorName();
            return operatorName;
        }
    }

    /**
     * 是否开启了悬浮窗
     *
     * @return
     */
    public String getSystemAlertWindow(Context context) {
        if(XXPermissions.isGranted(context, Permission.SYSTEM_ALERT_WINDOW)){
            return "1";
        }else{
            return "2";
        }
    }

    /**
     * 是否开启了蓝牙
     *
     * @return
     */
    public String getOpenBluetooth(Context context) {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
            return "1";
        }else{
            return "2";
        }
    }

    /**
     * APP 当前网络环境
     *
     * @return
     */
    public String getNetworkTypeName(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        String typeName = networkInfo.getTypeName();
        if (ConnectivityManager.TYPE_MOBILE == networkInfo.getType()) {
            return "流量";
        }
        return typeName;
    }

    /**
     * Android 系统版本
     *
     * @return
     */
    public String getSystemAndroidVersionCode() {
        return android.os.Build.VERSION.RELEASE;
    }

    /**
     * 手机品牌
     *
     * @return
     */
    public String getSystemAndroidMobilePhoneBrand() {
        return android.os.Build.BRAND;
    }

    /**
     * 系统版本号
     *
     * @return
     */
    public String getSystemAndroidSystemVersionCode() {
        return android.os.Build.DISPLAY;
    }

    /**
     * 获取手机安装应用列表
     *
     * @param context
     * @return
     */
    public List<PackageInfo> getAllApps(Context context) {
        List<PackageInfo> apps = new ArrayList<>();
        List<PackageInfo> packlist;
        PackageManager pManager = context.getPackageManager();
        // 获取手机内所有应用
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
             packlist = pManager.getInstalledPackages(PackageManager.PackageInfoFlags.of(0));
        } else {
             packlist = pManager.getInstalledPackages(0);
        }
        for (int i = 0; i < packlist.size(); i++) {
            PackageInfo pak = (PackageInfo) packlist.get(i);

            // 判断是否为非系统预装的应用程序
            // 这里还可以添加系统自带的，这里就先不添加了，如果有需要可以自己添加
            // if()里的值如果<=0则为自己装的程序，否则为系统工程自带
            if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) <= 0) {
                // 添加自己已经安装的应用程序
                apps.add(pak);
            }

        }
        return apps;
    }

    /**
     * 获取手机安装应用列表
     *
     * @param context
     * @return
     */
    public List<PackageInfo> getAllSystemApps(Context context) {
        List<PackageInfo> apps = new ArrayList<>();
        PackageManager pManager = context.getPackageManager();
        // 获取手机内所有应用
        List<PackageInfo> packlist = pManager.getInstalledPackages(0);
        for (int i = 0; i < packlist.size(); i++) {
            PackageInfo pak = (PackageInfo) packlist.get(i);
            // 判断是否为非系统预装的应用程序
            // 这里还可以添加系统自带的，这里就先不添加了，如果有需要可以自己添加
            // if()里的值如果<=0则为自己装的程序，否则为系统工程自带
            if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) > 0) {
                // 添加自己已经安装的应用程序
                apps.add(pak);
            }

        }
        return apps;
    }

    public String getOaId(Context context) {
        return DeviceIdentifier.getOAID(context);
    }

    public long getLastLoginTimeByPackageName(Context context, String packageName) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);

            // 安装时间（第一次安装时间）
            long firstInstallTime = packageInfo.firstInstallTime;
            Date installDate = new Date(firstInstallTime);

            // 更新时间（最后一次更新时间）
            long lastUpdateTime = packageInfo.lastUpdateTime;
            Date updateDate = new Date(lastUpdateTime);

            // 将毫秒数转换为实际日期格式或其他你需要的格式
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String installDateString = dateFormat.format(installDate);
            String updateDateString = dateFormat.format(updateDate);

            // 打印或在界面上显示安装时间和更新时间
            Log.d("WeChat Install Time", installDateString);
            Log.d("WeChat Update Time", updateDateString);
            return firstInstallTime;

        } catch (PackageManager.NameNotFoundException e) {
            // 微信没有安装在设备上 或者 发生了其他错误
            e.printStackTrace();
            return -1L;
        }
    }
//        return 1704978093000L;
//    }


    public static int safeParseInt(String value, int defaultValue) {
        if (TextUtils.isEmpty(value)) {
            return defaultValue;
        }
        try {
            return Integer.parseInt(value.trim());
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }
    private static final String DATE_FORMAT = "yyyy-MM-dd";
    public void saveNextClickCount(Context context ,int count) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
        String today = dateFormat.format(new Date());
        String value = today + ":" + count;

        SharedPreferences sp = context.getSharedPreferences("setting", MODE_PRIVATE);
        SharedPreferences.Editor ed = sp.edit();
        ed.putString(RedisEnum.NEXTBUTTOMCLICKNUMS.getKey(), (String) value);//保存token
        ed.commit();
    }

}
